#pragma once
#include <iostream>
#include<memory>
#include"epoller.hpp"
#include"listener.hpp"
#include"Connetion.hpp"
#include<unordered_map>
#include "log.hpp"
class tcpserver
{
    const static int _revs_num = 128;
    private:
    bool isConnectionExist(std::shared_ptr<Connection> &conn)
    {
        auto iter = _connections.find(conn->GetFD());
        if(iter == _connections.end())
        return false;
        else
        return true;
    }
    public:
tcpserver():_epoller_ptr(std::make_unique<epoller>())
,_isrunning(false)
{}
bool IsConnEmpty()
{
    return _connections.empty();
}
void start()
{
    if(IsConnEmpty())
    {
        return ;
    }
    _isrunning = true;
    while(_isrunning)
    {
        int timeout = 1000;
        int n = _epoller_ptr->Waitevents(_revs,_revs_num,timeout);
        for(int i = 0;i<n;i++)
        {
            
        }
    }
    _isrunning = false;
}
void addconnection(std::shared_ptr<Connection> &conn)
{
    //不要重复添加conn
    if(isConnectionExist(conn))
    {
        LOG(loglevel::WARN)<<"connection is existing";
        return ;
    }
    //将conn对应的fd与关心的事件，写透到内核中
    uint32_t events = conn->Getevents();
    int sockfd = conn->GetFD();
    _epoller_ptr->AddEvent(events,sockfd);
    //将具体的connection添加到哈希表中
    _connections[sockfd] = conn;
}
~tcpserver()
{}
private:
//有一个epoll模型
std::unique_ptr<epoller> _epoller_ptr;
// //监听模块
// std::shared_ptr<listener>_listener_ptr;
//管理一下未来获取到的的所有fd
std::unordered_map<int,std::shared_ptr<Connection>> _connections;

bool _isrunning;

//就绪的所有事件
struct epoll_event _revs[ _revs_num];
};